package com.yilin.tms.core.components.interceptor;

import com.yilin.commons.util.JsonUtil;
import com.yilin.tms.core.application.AppUtil;
import com.yilin.tms.core.commons.constant.HttpConstant;
import com.yilin.tms.core.commons.utils.UserUtil;
import com.yilin.tms.core.commons.base.BaseCode;
import com.yilin.tms.core.commons.annotation.*;
import com.yilin.tms.core.entity.system.handle.OperateLog;
import com.yilin.tms.core.components.repository.OperateLogRepository;
import com.yilin.tms.core.entity.user.account.Account;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;

/**
 * 日志拦截器
 */
@Configuration
public class LoggerInterceptor extends HandlerInterceptorAdapter {

    @Lazy
    @Resource
    private OperateLogRepository operateLogRepository;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        if (!(handler instanceof HandlerMethod)) {
            return responseErr(response, BaseCode.RES_NOT_EXIST, "请求的链接地址不存在");
        }
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        String customerIp = AppUtil.getIp(request);
        //#### 进行用户鉴权监控
        SkipLoginVerify skipLoginVerify = handlerMethod.getMethodAnnotation(SkipLoginVerify.class);
        if (skipLoginVerify != null) return true;
        String requestToken = request.getHeader(HttpConstant.TOKEN);
        Account loginUser = UserUtil.getLoginUser(requestToken);
        boolean mobile = request.getHeader(HttpConstant.MOBILE)!=null;
        //if (loginUser!=null) saveLog(loginUser, mobile, customerIp, request.getRequestURI());
        //### 操作刷新保存 移动端就不要设置啦
        if(!mobile) UserUtil.updateTokenAccessTime(requestToken);
        return true;
    }

    private void saveLog(Account loginUser, boolean mobile, String customerIp, String operateSite) {
        OperateLog operateLog = new OperateLog();
        operateLog.setOptToken(loginUser.getToken());
        operateLog.setOptUserId(loginUser.getId());
        operateLog.setOptUserName(loginUser.getName() == null ? loginUser.getUsername() : loginUser.getName());
        operateLog.setOptDeviceType(mobile ? OperateLog.DeviceType.mobile : OperateLog.DeviceType.web);
        operateLog.setSuperiorPlatId(loginUser.getSuperiorPlatId());
        operateLog.setOptIp(customerIp);
        operateLog.setOptTime(new Date());
        operateLog.setOperateSite(operateSite);
//        operateLogRepository.save(operateLog);
    }

    //返回前台数据
    private boolean responseErr(HttpServletResponse response, Integer code, String msg) {
        try {
            Map<String, Object> returnData = new HashMap<>();
            response.setCharacterEncoding("UTF-8");//设置字符集为'UTF-8'
            response.setContentType("application/json");//设置格式为text/json 
            returnData.put(HttpConstant.SUCCESS, false);
            returnData.put(HttpConstant.MSG, msg);
            returnData.put(HttpConstant.CODE, code);
            PrintWriter write = response.getWriter();
            write.write(JsonUtil.objectToJson(returnData));
            write.flush();
            write.close();
            return false;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }


}
